package org.naigu.peach.biz.impl;

import java.util.List;
import java.util.UUID;

import org.naigu.peach.biz.enums.UserStatusEnum;
import org.naigu.peach.biz.form.RegForm;
import org.naigu.peach.biz.util.Md5Util;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import org.naigu.peach.biz.UserBiz;
import org.naigu.peach.dal.dao.UserDAO;
import org.naigu.peach.dal.dataobject.UserDO;
import guda.grape.autogen.common.page.BaseQuery;
import guda.grape.autogen.common.page.BizResult;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;

import javax.mail.internet.MimeMessage;

public class UserBizImpl implements UserBiz{

    private final static Logger logger = LoggerFactory.getLogger(UserBizImpl.class);

    @Autowired
    private UserDAO userDAO;
    @Autowired
    private JavaMailSender mailSender;

    public BizResult detail(long id) {
        BizResult bizResult = new BizResult();
        try{
            UserDO userDO = userDAO.getUserById(id);
            bizResult.data.put("userDO", userDO);
            bizResult.success = true;
        }catch(Exception e){
            logger.error("query User error",e);
        }
        return bizResult;
}

    public BizResult list(BaseQuery baseQuery) {
        BizResult bizResult = new BizResult();
        try {
            int totalCount = userDAO.countForPage(baseQuery);
            baseQuery.setTotalCount(totalCount);
            List<UserDO> userList = userDAO.selectForPage(baseQuery);
            bizResult.data.put("userList", userList);
            bizResult.data.put("query", baseQuery);
            bizResult.success = true;
        } catch (Exception e) {
            logger.error("view User list error", e);
        }
            return bizResult;
     }

    public BizResult delete(long id) {
        BizResult bizResult = new BizResult();
        try {
            userDAO.delUserById(id);
            bizResult.success = true;
        } catch (Exception e) {
            logger.error("delete user error", e);
        }
        return bizResult;
    }

    public BizResult create(UserDO userDO) {
        BizResult bizResult = new BizResult();
        try {
            long id = userDAO.insert(userDO);
            bizResult.data.put("id", id);
            bizResult.success = true;
        } catch (Exception e) {
            logger.error("create User error", e);
        }
        return bizResult;
    }

    @Override
    public BizResult update(UserDO userDO) {
        BizResult bizResult = new BizResult();
        try {
            userDAO.updateByIdSelective(userDO);
            bizResult.success = true;
        } catch (Exception e) {
            logger.error("update User error", e);
        }
        return bizResult;
    }

    @Override
    public BizResult reg(RegForm regForm) {
        UserDO userDO = new UserDO();
        userDO.setEmail(regForm.getEmail());
        userDO.setUserName(regForm.getEmail());
        userDO.setPassword(Md5Util.md5(regForm.getPassword()));
        userDO.setEmail(regForm.getEmail());

        //userDO.setUserStatus(UserStatusEnum.normal.getVal());
        userDO.setUserStatus(UserStatusEnum.init.getVal());
        userDO.setRegCode(Md5Util.md5(UUID.randomUUID().toString()));
        BizResult bizResult = new BizResult();
        try {
            sendRegMail(userDO.getEmail(),userDO.getRegCode());
            userDAO.insert(userDO);
            bizResult.success = true;
        } catch (Exception e) {
            logger.error("update User error", e);
        }
        return bizResult;
    }


    private void sendRegMail(String toMail,String regCode) {

        JavaMailSenderImpl senderImpl = new JavaMailSenderImpl();
        MimeMessage mailMessage = senderImpl.createMimeMessage();

        //String render = uriBrokerService.getURIBroker("regValidLink").setQueryData("code", regCode).setQueryData("email", toMail).render();
        try {
            MimeMessageHelper messageHelper = new MimeMessageHelper(mailMessage,true,"utf-8");
            messageHelper.setTo(toMail);
            messageHelper.setFrom("gang0119@163.com");
            messageHelper.setSubject("API MOCK邮箱验证");//主题
            messageHelper.setText(mail_text.replaceAll("_VALID_URL_", ""), true);//邮件内容
            mailSender.send(mailMessage);
        } catch (Exception e) {
            logger.error("",e);
        }
    }

    @Override
    public BizResult validatorEmail(String email, String code) {
        BizResult bizResult = new BizResult();
        List<UserDO> userDOList = userDAO.selectByEmailAndRegCode(email, code);
        if (userDOList.size() == 0) {
            return bizResult;
        }
        UserDO userDO = userDOList.get(0);
        UserDO temp = new UserDO();
        temp.setUserId(userDO.getUserId());
        temp.setUserStatus(UserStatusEnum.normal.getVal());
        try {
            userDAO.updateByIdSelective(temp);
            bizResult.success = true;
        } catch (Exception e) {
            logger.error("update User error", e);
        }
        return bizResult;
    }

    public static final String mail_text = "\n" +
            "<html>\n" +
            "<head>\n" +
            "    <title>\n" +
            "        API DOCS\n" +
            "    </title>\n" +
            "    <meta charset=\"UTF-8\">\n" +
            "    </head>\n" +
            "  <body>\n" +
            "    <style type=\"text/css\">.qmbox .m-box{font-family: \"Microsoft YaHei\",\"Helvetica Neue\",\"Luxi Sans\",\"DejaVu Sans\",Tahoma,\"Hiragino Sans GB\",STHeiti,Arial,sans-serif; width:600px;margin:30px 0;border:1px solid #ddd;color:#888;font-size:14px;}\n" +
            ".qmbox .m-header{height:60px;line-height:60px;background: #18c1d6;}\n" +
            ".qmbox .m-header .logo{width:160px;margin:12px 0 0 20px}\n" +
            ".qmbox .m-box .bd{background: #fff;padding:40px}\n" +
            ".qmbox .m-box .footer{line-height:20px;color:#999;background: #f5f5f5;font-size:12px;border-top:1px solid #ddd;padding:10px 20px}\n" +
            ".qmbox .m-box .footer p{margin:0}\n" +
            ".qmbox .m-box .bd h1{font-weight: 700;}\n" +
            ".qmbox .m-box .tex{line-height:25px;font-size:14px;}\n" +
            ".qmbox .m-box .tex p{margin-bottom:5px}\n" +
            ".qmbox .m-box .tex em{background:#eee;}\n" +
            ".qmbox .m-box .link{text-align: right;padding:50px 0 0;color:#999}\n" +
            ".qmbox .m-box .btn{text-decoration: none; display: inline-block;padding:5px 25px;background: #18C1D6;color:#fff;border-radius:5px;}\n" +
            "</style>\n" +
            "<div class=\"m-box\">\n" +
            "    <div class=\"bd\">\n" +
            "        <h1>尊敬的 <a href=\"mailto:foodoon@qq.com\" target=\"_blank\">foodoon@qq.c<wbr>om</a>， 您好！</h1>\n" +
            "        <div class=\"tex\">\n" +
            "            <p>请确认本邮件是否是你需要的。</p>\n" +
            "            <p>请点击下面的地址，根据提示进行邮箱激活：</p>\n" +
            "\n" +
            "            <p>地址：<a href=\"_VALID_URL_\" target=\"_blank\">点击完成邮箱验证</a>\n" +
            "            </p>\n" +
            "            <p> 如果单击链接没有反应，请复制下面链接到浏览器窗口中，或直接输入链接。</p>\n" +
            "            <em><a href=\"_VALID_URL_\" target=\"_blank\"></em>\n" +
            "            <p> 如您未提交该申请，请不要理会此邮件，对此为您带来的不便深表歉意。</p>\n" +
            "        </div>\n" +
            "        <div class=\"link\">\n" +
            "            API MOCK\n" +
            "            <br></div>\n" +
            "    </div>\n" +
            "    <div class=\"footer\">\n" +
            "\n" +
            "        <p> 如有疑问，致电客服中心 <span style=\"border-bottom:1px dashed #ccc;z-index:1\" t=\"7\" onclick=\"return false;\" data=\"17098158159\">17098158159</span>, 方便您解决问题。\n" +
            "            <br> 或者发邮件到 <a href=\"mailto:apimock@163.com\" target=\"_blank\">apimock@163.com</a>，感谢您的支持。\n" +
            "        </p>\n" +
            "    </div>\n" +
            "</div>\n" +
            "</body>\n" +
            "</html>";


}
